//
//  LLUserAccountViewModel.swift
//  新浪微博
//
//  Created by mac on 16/5/23.
//  Copyright © 2016年 mac.com. All rights reserved.
//

import UIKit
import SVProgressHUD
private let userInfoKey = "com.itheima.userInfoKey"
class LLUserAccountViewModel: NSObject {
    static let sharedAccountViewModel:LLUserAccountViewModel = LLUserAccountViewModel()
    var userAccount:LLUserAccount?
    private override init() {
        super.init()
userAccount = loadUserAccount()
    }
    var headURL: NSURL? {
        get {
            return NSURL(string: userAccount?.avatar_large ?? "")
        }
    }
    //通过一判断用户是否登录的计算型属性 来解决 每次都需要判断的问题
    //计算型属性 每次调用都会执行
    var userLogin:Bool{
        if userAccount?.expires_date?.compare(NSDate()) == .OrderedDescending {
            return true
        }
    //如果过期  需要将 userAccount 设置为 nil
        userAccount = nil
        return false

        }
    
}
extension LLUserAccountViewModel{
    
    //使用code 加载token 
    func loadAccenToken(code: String, finished: (isSuccess: Bool) -> ()){
        LLNetworkTools.shardTools.loadAccenToken(code) { (responseObject, error) -> () in
            if error != nil{
                print(responseObject,error)
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
               finished(isSuccess: false)
                return
            }
            self.loadUserInfor(responseObject, finished: finished)

        }
        
}
    //请求用户数据
      private  func loadUserInfor(response: AnyObject? ,finished: (isSuccess: Bool) -> ()){
        guard let result = response as? [String : AnyObject] else{
        return
        }
        LLNetworkTools.shardTools.loadUserInfor(result) { (responseObject, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                print(error)
                finished(isSuccess: false)
                return
            }
            guard var dict = responseObject as?[String:AnyObject] else{
                return
            }
            for (key,value) in result{
                dict[key] = value
            }
            self.userAccount = LLUserAccount(dict: dict)
            self.saveUserAccount(dict)
            finished(isSuccess: true)
        }

        }


}

extension LLUserAccountViewModel{
    
    //存数据
    func saveUserAccount(dict:[String:AnyObject]){
    let user = LLUserAccount(dict: dict)
    let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
    let userInfor = user.dictionaryWithValuesForKeys(keys)
    let userDefault = NSUserDefaults.standardUserDefaults()
        userDefault.setObject(userInfor, forKey: userInfoKey)
    userDefault.synchronize()
    
    }
    //取数据
   func loadUserAccount() -> LLUserAccount?{
    guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as?[String:AnyObject] else{
    return nil
    }
    let user = LLUserAccount(dict: dict)
    return user
    
    
    }
}